package com.fancylargo.crowd.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.ServerWebExchange;

/**
 * 解决跨域配置问题
 * @Author chaigq
 * @Date 2020/7/14 11:45 下午
 * @Version 1.0
 */
// 标注是配置类
@Configuration
public class FancyCorsConfiguration {
    // @Bean 会将配置加入到容器中，使全局解决跨域问题
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 配置跨域
        // 允许那些头跨域
        corsConfiguration.addAllowedHeader("*");
        // 允许那些请求方式跨域
        corsConfiguration.addAllowedMethod("*");
        // 允许那些请求来源跨域
        corsConfiguration.addAllowedOrigin("*");
        // 是否允许携带cookie跨域,防止跨域请求丢失cookie信息
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}
